///Users/sanshisan/Documents/projects/溯源项目/盱眙龙虾/XuYiLobster.xcodeproj
//  XYShareManger.swift
//  XuYiLobster
//
//  Created by 叁拾叁 on 2020/8/5.
//  Copyright © 2020 叁拾叁. All rights reserved.
//

import UIKit
import Toast
import Kingfisher

enum ShareState {
    case success
    case cancel
    case fail
}

class XYShareManger: NSObject {
    
    class func toShare(_ body: [String: Any], _ currentVC: HSWebViewController) {
        let sharePlatformType = body["sharePlatformType"] as? Int ?? 0 // 1 微信 2 其他
        let shareContentType = body["shareContentType"] as? Int ?? 0 // 1 链接 2 图片
        let shareDescr = body["shareDescr"] as? String ?? ""
        let shareImage = body["shareImage"] as? String ?? ""
        let shareTitle = body["shareTitle"] as? String ?? ""
        let shareUrl = body["shareUrl"] as? String ?? ""
        
        let model = XYShareModel()
        if sharePlatformType == 1 {
            model.sharePlatformType = .wechatSession
        }
        if shareContentType == 1 {
            model.shareContentType = .url
        }
        model.shareTitle = shareTitle
        model.shareDescr = shareDescr
        model.shareUrl = shareUrl
        model.currentVC = currentVC
        UIImageView().kf.setImage(with: URL(string: shareImage), placeholder: UIImage(named: "AppIcon"), options: .none, progressBlock: nil) { (image, error, cacheType, url) in
            model.shareImage = image
            XYShareManger.toShareClient(model: model) { (state) in
                
            }
        }
    }
    
    class func toShareClient(model: XYShareModel, completed: ((ShareState) -> Void)?) {
        
        switch model.sharePlatformType {
        
        case .wechatTimeLine:
            if UMSocialManager.default()?.isInstall(UMSocialPlatformType.wechatSession) == true || UMSocialManager.default()?.isSupport(UMSocialPlatformType.wechatSession) == true {
                self.shareWebPageToPlatformType(model: model) { (state) in
                    completed?(state)
                }
            } else {
                UIAlertView.init(title: "未安装微信客户端, 或者未登录微信", message: nil, delegate: nil, cancelButtonTitle: "我知道了").show()
            }
        case .wechatSession:
            if UMSocialManager.default()?.isInstall(UMSocialPlatformType.wechatSession) == true || UMSocialManager.default()?.isSupport(UMSocialPlatformType.wechatSession) == true {
                self.shareWebPageToPlatformType(model: model) { (state) in
                    completed?(state)
                }
            } else {
                UIAlertView.init(title: "未安装微信客户端, 或者未登录微信", message: nil, delegate: nil, cancelButtonTitle: "我知道了").show()
            }
        case .wechatFavorite:
            if UMSocialManager.default()?.isInstall(UMSocialPlatformType.wechatSession) == true || UMSocialManager.default()?.isSupport(UMSocialPlatformType.wechatSession) == true {
                self.shareWebPageToPlatformType(model: model) { (state) in
                    completed?(state)
                }
            } else {
                UIAlertView.init(title: "未安装微信客户端, 或者未登录微信", message: nil, delegate: nil, cancelButtonTitle: "我知道了").show()
            }
        case .userDefine_Begin:
            let pastboard = UIPasteboard.general
            pastboard.string = model.shareUrl
        default:
            break
        }
    }

    class func shareWebPageToPlatformType(model: XYShareModel, completed: ((ShareState) -> Void)?) {
        
        // 创建分享消息对象
        let messageObject: UMSocialMessageObject = UMSocialMessageObject.init()
        if model.shareContentType == .image {
            // 创建网页内容对象
            let shareObject: UMShareImageObject = UMShareImageObject()
            // 设置网页地址
            shareObject.shareImage = model.shareImage
            // 分享消息对象设置分享内容对象
            messageObject.shareObject = shareObject
        } else if model.shareContentType == .url {
            // 创建网页内容对象
            let shareObject: UMShareWebpageObject = UMShareWebpageObject.shareObject(withTitle: model.shareTitle, descr: model.shareDescr, thumImage: model.shareImage)
            // 设置网页地址
            shareObject.webpageUrl = model.shareUrl
            // 分享消息对象设置分享内容对象
            messageObject.shareObject = shareObject
        }
        
        // 调用分享接口
        UMSocialManager.default()?.share(to: model.sharePlatformType!, messageObject: messageObject, currentViewController: model.currentVC, completion: { (data, error) in
            if error != nil {
                if true == error?.localizedDescription.contains("未能完成操作") {
                    completed?(.cancel)
                    model.currentVC!.view.makeToast("分享取消", duration: 1.0, position: nil)
                } else {
                    print("************Share fail with error %@*********\(error!)")
                    completed?(.fail)
                    model.currentVC!.view.makeToast("分享失败, 错误信息: \(error!.localizedDescription)", duration: 1.0, position: nil)
                }
            } else {
                let resp: UMSocialShareResponse? = data as? UMSocialShareResponse
                if let r = resp {
                    // 分享结果消息
                    print("response message is \(r.message ?? "")")
                    // 第三方原始返回的数据
                    print("response originalResponse data is \(r.originalResponse!)")
                    completed?(.success)
                    model.currentVC!.view.makeToast("分享成功", duration: 1.0, position: nil)
                }
            }
        })
    }
}
